<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index</title>
<%
	//引入服务器绝对路径
	pageContext.setAttribute("App_Path", request.getContextPath());
%>
<!-- 引入jQuery -->
<%-- <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> --%>
<%-- <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
 --%>
<script type="text/javascript"
	src="${App_Path }/static/js/jquery-3.2.1.js"></script>
<!-- 引入样式 -->
<link
	href="${App_Path }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
	rel="stylesheet">
<script
	src="${App_Path }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

	<script type="text/javascript">
	
		//保存总记录数
		var totalRecond,currentPage;
	
		$(function() {
			//页面跳转
			to_page(1);
			
			
			//新增按钮点击事件
			empAdd();
			//保存操作按钮点击事件
			sava_btn();
			//用户名框修改事件
			checkEmpName();
			//更新操作用户名框修改校验			
			//checkUpdateEmpName();
			
			//编辑按钮模态框
			emp_update();
			
			//保存更新按钮
			update_emp_btn();
			
			//单个删除
			deleteEmp();
			
			//多选
			checkBox();
			
			//单选
			check_item();
			
			//批量删除
			delete_bathch();
			
		});

		function to_page(pageNum) {
			$.ajax({
				url : "${App_Path}/emps",
				data : "pageNumber=" + pageNum,
				type : "GET",
				success : function(result) {
					//console.log(result);
					//解析员工数据
					build_emp_table(result);

					//解析分页信息
					build_page_info(result);

					//显示页码条
					build_page_nav(result);
					
				}
			});
		}

		function build_emp_table(result) {
			//每次方法执行前，应清空之前的数据，防止叠加显示
			$("#emps_table tbody").empty();

			var emps = result.extend.pageInfo.list;
			$.each(emps, function(index, item) {
				//alert(item.empName);
				//多选框
				var checkbox = $("<td><input type='checkbox' class='check_item'/></td>");
				var empIdTd = $("<td></td>").append(item.empId);
				var empNameTd = $("<td></td>").append(item.empName);
				var genderTd = $("<td></td>").append(item.gender);
				var emailTd = $("<td></td>").append(item.email);
				var deptNameTd = $("<td></td>")
						.append(item.department.deptName);
				//添加按钮
				var editBtn = $("<button></button>").addClass(
						"btn btn-primary  btn-sm").append("<span></span>")
						.addClass("glyphicon glyphicon-pencil edit_btn").append("编辑");
				//为按钮所管理的员工的id
				editBtn.attr("emp_id",item.empId);
				var delBtn = $("<button></button>").addClass(
						"btn btn-danger  btn-sm").append("<span></span>")
						.addClass("glyphicon glyphicon-trash del_btn").append("删除");
				//为删除所管理的员工的id
				delBtn.attr("emp_id",item.empId);
				
				var btn = $("<td></td>").append(editBtn).append(delBtn);

				$("<tr></tr>").append(checkbox)
						.append(empIdTd)
						.append(empNameTd)
						.append(genderTd)
						.append(emailTd)
						.append(deptNameTd)
						.append(btn)
						.appendTo("#emps_table tbody");
				
			});
		}

		//生成页码信息
		function build_page_info(result) {

			$("#page_info_area").empty();

			$("#page_info_area").append(
					"当前第" + result.extend.pageInfo.pageNum + "页,共"
							+ result.extend.pageInfo.pages + "页,总"
							+ result.extend.pageInfo.total + "条记录");
			
			//保存总记录数
			totalRecond = result.extend.pageInfo.total;
			currentPage = result.extend.pageInfo.pageNum;
		}

		//生成页码条标签
		function build_page_nav(result) {

			$("#page_nav_area").empty();

			//构建<nav>标签
			var nav = $("<nav></nav>");
			//构建<ul>标签
			var ul = $("<ul></ul>").addClass("pagination");
			//构建标签<li>
			var firstPageLi = $("<li></li>").append(
					$("<a></a>").append("首页").attr("href", "#"));
			var prePageLi = $("<li></li>").append(
					$("<a></a>").append("&laquo;").attr("href", "#"));

			if (result.extend.pageInfo.hasPreviousPage == false) {
				firstPageLi.addClass("disabled");
				prePageLi.addClass("disabled");
			}

			//添加点击翻页事件
			firstPageLi.click(function() {
				to_page(1);
			});
			prePageLi.click(function() {
				to_page(result.extend.pageInfo.pageNum - 1);
			});

			var nextPageLi = $("<li></li>").append(
					$("<a></a>").append("&raquo;").attr("href", "#"));
			var lastPageLi = $("<li></li>").append(
					$("<a></a>").append("末页").attr("href", "#"));

			if (result.extend.pageInfo.hasNextPage == false) {
				nextPageLi.addClass("disabled");
				lastPageLi.addClass("disabled");
			}

			nextPageLi.click(function() {
				to_page(result.extend.pageInfo.pageNum + 1);
			});
			lastPageLi.click(function() {
				to_page(result.extend.pageInfo.pages);
			});

			//添加首页和前一页标签
			ul.append(firstPageLi).append(prePageLi);

			//遍历页码添加到页码条标签
			$.each(result.extend.pageInfo.navigatepageNums, function(index,
					item) {
				var numLi = $("<li></li>").append(
						$("<a></a>").append(item).attr("href", "#"));
				//当前页码高亮显示
				if (result.extend.pageInfo.pageNum == item) {
					numLi.addClass("active");
				}
				//定义点击事件
				numLi.click(function() {
					to_page(item);
				});

				ul.append(numLi);
			});

			//添加后一页和末页标签
			ul.append(nextPageLi).append(lastPageLi);

			//把ul标签添加到nav标签
			nav.append(ul);

			$("#page_nav_area").append(nav);
		}

		//新增按钮点击事件,弹出模态框
		function empAdd() {
			
			$("#emp_add_btn").click(function() {
				//发送ajax请求获取部门信息
				getDepts("#add_dept_select");
				
				//首先清除表单信息,使用dom对象
				$("#addEmp_form")[0].reset();
				//清除表单样式
				$("#addEmp_form").find("*").removeClass("has-success has-error");
				//清除表单提示信息
				$("#addEmp_form").find(".help-block").text("");
				
				//弹出模态框
				$('#empAdd_Modal').modal({
					backdrop : "static"
				});
			});
		}
		
		//点击编辑按钮弹出模态框
		function emp_update() {
			$(document).on("click",".edit_btn",function(){
				//alert("edit");
				//1.查出部门列表并显示
				 getDepts("#update_dept_select");
				//2.查出员工信息并显示
				 getEmpInfo($(this).attr("emp_id"));
				//给保存更新按钮绑定员工id值
				$("#update_emp_btn").attr("emp_id",$(this).attr("emp_id"))
				//弹出模态框
				 $('#empUpdate_Modal').modal({
						backdrop : "static"
					});
				
			});
		}
		
		function getEmpInfo(id) {
			$.ajax({
				url:"${App_Path}/emp/" + id,
				type:"GET",
				success:function(result){
					//console.log(result);
					var empData = result.extend.emp;
					$("#updateEmpName").val(empData.empName);
					$("#updateEmail").val(empData.email);
					$("#empUpdate_Modal input[name=gender]").val([empData.gender]);
					$("#empUpdate_Modal select").val([empData.dId]);
				}
			});
		}
		
		//发送ajax请求获取部门信息并显示在下拉列表中
		function getDepts(ele){
			//清空原有下拉列表的值
			$(ele).empty();
			$.ajax({
				url:"${App_Path}/depts",
				type:"GET",
				success:function(result){
					/*{"code":100,"msg":"请求成功！","extend":{"depts":[{"deptId":1,"deptName":"研发部"},
						{"deptId":2,"deptName":"测试部"},{"deptId":3,"deptName":"产品部"}]}}
					*/
					//console.log(result);
					//$("depts_select").append
					$.each(result.extend.depts,function(index, dept){
						var deptEle = $("<option></option>").append(dept.deptName).attr("value",dept.deptId);
						deptEle.appendTo(ele);
					});
					
				}
			});
		}
		
		
		//保存员工按钮点击事件
		function sava_btn(){
			$("#sava_emp_btn").click(function(){
				
				//将表单数据转化城字符串提交给服务器
				//1.前端数据校验
				if(!validate_add_form() ){
					return false;
				}
				
				//2.ajax检查用户名是否可用
				if ($(this).attr("ajax-validate") == "error") {
					return false;
				}
				
				//将表单内容转化为字符串封装传入到controller的函数入参
				var data = $("#addEmp_form").serialize();
				//2.发送ajax请求
				$.ajax({
					url:"${App_Path}/emp",
					type:"POST",
					data:data,
					success:function(result){
						//alert(result.msg + "即将跳转到您添加的记录！");
						//对后端的JSR303校验结果进行解析
						if (result.code == 100) {
							
							alert(result.msg + "即将跳转到您添加的记录！");
							
							//保存成功后跳转到最后一页显示刚刚保存的数据
							//1.关闭模态框
							$('#empAdd_Modal').modal('hide');
							//2.发送ajax请求跳转到最后一页，把参数设为记录数，当大于最大页数时，将到达最后一页
							to_page(totalRecond);
						} else {
							//JSR校验失败
							//console.log(result);
							if (undefined != result.extend.filedError.email) {
								//显示邮箱错误信息
								show_validate_msg("#inputEmial","has-error",result.extend.filedError.email);
							}
							if (undefined != result.extend.filedError.empName) {
								//显示用户名错误信息
								show_validate_msg("#inputEmpName","has-error",result.extend.filedError.empName);
							}
						}
					}
						
				});
				
			});
		}
		
		//更新按钮点击事件
		function update_emp_btn() {
			$("#update_emp_btn").click(function() {
				//将表单数据转化城字符串提交给服务器
				//1.前端数据校验
				/*
				if(!validate_update_form()){
					return false;
				}
				*/
				//2.ajax检查用户名是否可用
				if ($(this).attr("ajax-validate") == "error") {
					return false;
				}
				
				//发送ajax请求
				$.ajax({
					url:"${App_Path}/emp/" + $(this).attr("emp_id"),
					//type:"POST",
					//data:$("#updateEmp_form").serialize() + "&_method=PUT",
					type:"PUT",
					data:$("#updateEmp_form").serialize(),
					success:function(result){
						//alert(result.msg);
					
						if (result.code == 100) {
							
							alert(result.msg + "即将跳转到您添加的记录！");
							
							//保存成功后跳转到最后一页显示刚刚保存的数据
							//关闭模态框
							$("#empUpdate_Modal").modal("hide");
							//回到当前页
							to_page(currentPage);
							
						} else {
							//JSR校验失败
							//console.log(result);
							if (undefined != result.extend.filedError.email) {
								//显示邮箱错误信息
								show_validate_msg("#updateEmail","has-error",result.extend.filedError.email);
							}
							if (undefined != result.extend.filedError.empName) {
								//显示用户名错误信息
								show_validate_msg("#updateEmpName","has-error",result.extend.filedError.empName);
							}
						}
					}
				});
			});
		}
		
		//添加操作的表单校验
		function validate_add_form(){
			
			//校验用户名
			var empName = $("#inputEmpName").val();
			var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
			if(!regName.test(empName)){
				//alert("用户名必须是2-5个汉字或6-16位字母或数字组合！");
				show_validate_msg("#inputEmpName","has-error","用户名必须是2-5个汉字或6-16位字母或数字组合！")
				return false;
			}else{
				show_validate_msg("#inputEmpName","has-success","");
			}
			
			//校验邮箱
			var email = $("#inputEmial").val();
			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
			if(!regEmail.test(email)){
				//alert("邮箱格式不正确！");
				show_validate_msg("#inputEmial","has-error","邮箱格式不正确！")
				return false;
			}else{
				show_validate_msg("#inputEmial","has-success","");
			}
			
			//alert("格式正确！");
			return true;
		}
		
		//更新操作的表单校验
		function validate_update_form(){
			
			//校验用户名
			var empName = $("#updateEmpName").val();
			var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
			if(!regName.test(empName)){
				//alert("用户名必须是2-5个汉字或6-16位字母或数字组合！");
				show_validate_msg("#updateEmpName","has-error","用户名必须是2-5个汉字或6-16位字母或数字组合！")
				return false;
			}else{
				show_validate_msg("#updateEmpName","has-success","");
			}
			
			//校验邮箱
			var email = $("#updateEmial").val();
			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
			if(!regEmail.test(email)){
				//alert("邮箱格式不正确！");
				show_validate_msg("#updateEmial","has-error","邮箱格式不正确！")
				return false;
			}else{
				show_validate_msg("#updateEmial","has-success","");
			}
			
			//alert("格式正确！");
			return true;
		}
		
		//优化显示校验信息
		function show_validate_msg(ele,status,msg){
			//清除原有的校验状态信息
			$(ele).parent().removeClass("has-success has-error");
			$(ele).next("span").text("");
			
			$(ele).parent().addClass(status);
			$(ele).next("span").text(msg);
		}
		
		//发送ajax请求验证用户名是否可用
		function checkEmpName() {
			$("#inputEmpName").change(function(){
				empName = this.value;
				$.ajax({
					url:"${App_Path}/checkUser",
					data:"empName=" + empName,
					type:"POST",
					success:function(result){
						if (result.code == 100) {
							//显示提示信息
							show_validate_msg("#inputEmpName","has-success","用户名可用");
							//将保存按钮disable
							$("#sava_emp_btn").attr("ajax-validate","success");
						}else{
							show_validate_msg("#inputEmpName","has-error",result.extend.back_validate);
							$("#sava_emp_btn").attr("ajax-validate","error");
						}
					}
				});
			});
		}
		
		//检查更新的用户名是否可用
		function checkUpdateEmpName() {
			$("#updateEmpName").change(function(){
				empName = this.value;
				$.ajax({
					url:"${App_Path}/checkUser",
					data:"empName=" + empName,
					type:"POST",
					success:function(result){
						if (result.code == 100) {
							//显示提示信息
							show_validate_msg("#updateEmpName","has-success","用户名可用");
							//将保存按钮disable
							$("#update_emp_btn").attr("ajax-validate","success");
						}else{
							show_validate_msg("#updateEmpName","has-error",result.extend.back_validate);
							$("#update_emp_btn").attr("ajax-validate","error");
						}
					}
				});
			});
		}
		
		//单个删除
		function deleteEmp() {
			
			$(document).on("click",".del_btn",function(){
				//alert("删除");
				var empName = $(this).parents("tr").find("td:eq(2)").text();
				if (confirm("确定删除【"+empName+"】吗？")) {
					$.ajax({
						url:"${App_Path}/emp/" + $(this).attr("emp_id"),
						type:"DELETE",
						success:function(result){
							alert(result.msg);
							
							to_page(currentPage);
						}
						
					});
				}
			});
		}
		
		//全选/全不选功能
		function checkBox() {
			$("#check_all").click(function(){
				//alert($(this).prop("checked"));
				$(".check_item").prop("checked",$(this).prop("checked"));
			});
		}
		
		//check_item
		function check_item() {
			$(document).on("click",".check_item",function(){
				//判断是否全选
				var flag = $(".check_item:checked").length == $(".check_item").length;
				$("#check_all").prop("checked",flag);
			});
		}
		
		//批量删除点击事件
		function delete_bathch() {
			$("#emp_del_btn").click(function() {
				//alert("删除！");
				var empNames = "";
				var del_ids = "";
				$.each($(".check_item:checked"),function(){
					empNames += $(this).parents("tr").find("td:eq(2)").text() + ",";
					//拼装id
					del_ids += $(this).parents("tr").find("td:eq(1)").text() + "-";
				});
				//去除多余的“，”
				empNames = empNames.substring(0,empNames.length-1);
				//去除多余的“-”
				del_ids = del_ids.substring(0,del_ids.length-1);
				
				//alert("确认删除【"+empNames+"】吗？");
				if (confirm("确认删除【"+empNames+"】吗？")) {
					$.ajax({
						url:"${App_Path}/emp/" + del_ids,
						type:"DELETE",
						success:function(result){
							alert(result.msg);
							to_page(currentPage);
						}
					});
				}
			
			});
		}
	</script>


	<!-- 编辑按钮的模态框Modal -->
	<div class="modal fade" id="empUpdate_Modal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">修改员工信息</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" id="updateEmp_form">
						<div class="form-group">
							<label for="updateEmpName" class="col-sm-2 control-label">EmpName</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="empName" id="updateEmpName" placeholder="empName">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="updateEmial" class="col-sm-2 control-label">Email</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="email" id="updateEmail" placeholder="email@qq.com">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">Gender</label>
							<div class="col-sm-10">
								<label class="radio-inline"> 
									<input type="radio" name="gender" id="genderRadio1" value="男">男
								</label>
								<label class="radio-inline"> 
									<input type="radio" name="gender" id="genderRadio2" value="女">女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">DeptName</label>
							<div class="col-sm-4">
								<!-- 只需提交部门id -->
								<select class="form-control" name="dId" id="update_dept_select">
								</select>
							</div>
						</div>
						
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="update_emp_btn">保存</button>
				</div>
			</div>
		</div>
	</div>
	<!-- 新增按钮的模态框Modal -->
	<div class="modal fade" id="empAdd_Modal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">添加员工</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" id="addEmp_form">
						<div class="form-group">
							<label for="inputEmpName" class="col-sm-2 control-label">EmpName</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="empName" id="inputEmpName" placeholder="empName">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="inputEmial" class="col-sm-2 control-label">Email</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="email" id="inputEmial" placeholder="email@qq.com">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">Gender</label>
							<div class="col-sm-10">
								<label class="radio-inline"> 
									<input type="radio" name="gender" id="genderRadio1" value="男">男
								</label>
								<label class="radio-inline"> 
									<input type="radio" name="gender" id="genderRadio2" value="女">女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">DeptName</label>
							<div class="col-sm-4">
								<!-- 只需提交部门id -->
								<select class="form-control" name="dId" id="add_dept_select">
								</select>
							</div>
						</div>
						
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="sava_emp_btn">保存</button>
				</div>
			</div>
		</div>
	</div>

	<%--搭建显示页面 --%>
	<div class="container">
		<%--标题行 --%>
		<div class="row">
			<div class="col-md-12">
				<h1>SSM-CRUD员工列表</h1>
			</div>
		</div>
		<%--按钮行 --%>
		<div class="row">
			<div class="col-md-4 col-md-offset-8">
				<button type="button" class="btn btn-primary" id="emp_add_btn">新增</button>
				<button type="button" class="btn btn-danger" id="emp_del_btn">删除</button>
			</div>
		</div>
		<%--列表行 --%>
		<div class="row">
			<div class="col-md-12">
				<table class="table table-hover" id="emps_table">
					<thead>
						<tr>
							<th>
								<input type="checkbox" id="check_all"/>
							</th>
							<th>empId</th>
							<th>empName</th>
							<th>gender</th>
							<th>email</th>
							<th>deptName</th>
							<th>operation</th>
						</tr>
					</thead>
					<tbody>

					</tbody>
				</table>
			</div>
		</div>
		<%--分页信息 页码行 --%>
		<div class="row">
			<%--文字信息 --%>
			<div class="col-md-6" id="page_info_area"></div>

			<%--页码条--%>
			<div class="col-md-6" id="page_nav_area"></div>
		</div>
	</div>

</body>
</html>